package com.zhongjianjian.zookeeper.service;
import com.zhongjianjian.redisLock.entity.TestStock;

import com.zhongjianjian.zookeeper.dao.ZkStockDao;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;
/**
 * @类名: com.zhongjianjian.zookeeper.service
 * @作者: lgt
 * @创建时间: 2020-02-28 19:38
 * @描述:
 **/
@Component
public class ZkStockService {
    @Autowired
    private ZkStockDao zkStockDao;

    public void lockStock(Map<String,String> map) throws Exception {

        //Zokkper的一个重试策略类
        RetryPolicy retryPolicy=new ExponentialBackoffRetry(3000,3);
        //如果是zookeeper集群的话 可以用逗号隔开去写（例如 192.168.137.1:2181,192.168.137.2:2181）
        CuratorFramework curatorFramework = CuratorFrameworkFactory.newClient("127.0.0.1:2181", retryPolicy);

        //启动客户端
        curatorFramework.start();

        //加入进程的互斥中
        InterProcessMutex interProcessMutex = new InterProcessMutex(curatorFramework, "/MYLOCK");

        //获取锁
        interProcessMutex.acquire();//获取锁的方法（如果获取不到的话，当前线程就会阻塞）

        //获取库存

        TestStock stock = zkStockDao.getStock(map);

        try{
            //判断库存是否充足
            if(stock.getStock()>=1){

                //减少库存
                stock.setStock(stock.getStock()-1);
                zkStockDao.updateStock(stock);

            }else{
                throw new RuntimeException("库存不足");
            }
        }finally {
            //释放锁
            interProcessMutex.release();//释放锁
            //关闭客户端
            curatorFramework.close();
        }
    }
}
